package com.hardson.toolkit.swing.print;

import java.awt.BasicStroke;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;

import lombok.Getter;
import lombok.Setter;

public class PreviewArea extends Component {

	private static final long serialVersionUID = -6384174997251439843L;

	private Preview preview;

	private PageFormat pageFormat;

	@Getter
	@Setter
	private int pageIndex;

	private int w;

	private int h;

	private final int marginX = 10;

	private final int marginY = 20;

	public PreviewArea(final Preview preview) {
		this.preview = preview;
		this.pageFormat = preview.getJob().pageDialog(preview.getJob().defaultPage());
		this.pageIndex = 0;
		this.w = (int) this.pageFormat.getWidth();
		this.h = (int) this.pageFormat.getHeight();
	}

	@Override
	public Dimension getPreferredSize() {
		return new Dimension(this.w + 2 * this.marginX, this.h + 2 * this.marginY);
	}

	@Override
	public void paint(final Graphics g) {
		Graphics2D g2 = (Graphics2D) g.create();
		g2.translate(this.marginX, this.marginY);
		g2.drawRect(0, 0, this.w, this.h);
		int ix = (int) (this.pageFormat.getImageableX() - 1);
		int iy = (int) (this.pageFormat.getImageableY() - 1);
		int iw = (int) (this.pageFormat.getImageableWidth() + 1);
		int ih = (int) (this.pageFormat.getImageableHeight() + 1);
		g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10f,
				new float[] { 5, 5 }, 0f));
		g2.drawRect(ix, iy, iw, ih);
		try {
			this.preview.print(g2, this.pageFormat, this.pageIndex);
		} catch (PrinterException e) {
			e.printStackTrace();
		}
		g2.dispose();
		this.preview.getHeader().setPaintable(true);
		this.preview.getHeader().repaint();
	}
}
